// lib/pages/home.dart
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/category.dart';
import 'package:multi_shop/models/product.dart';
import 'package:multi_shop/services/product_api.dart';
import '../widgets/goods.dart';

class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  final _api = ProductApi();
  final Map<int, List<Product>> _cache = {};
  @override
  bool get wantKeepAlive => true;
  List<Product> _list = [];
  List<Category> _categories = [];
  int categoryIndex = 0;
  TabController? _tabController;
  bool _loading = false;
  String? _error;

  _HomeState() {
    debugPrint('HomeState constructor ${identityHashCode(this)}');
  }
  @override
  void initState() {
    super.initState();
    _initData();
  }

  // 切换分类
  void _handleTabChange() {
    if (_tabController!.indexIsChanging) return; // 避免重复触发
    final index = _tabController!.index;
    if (index == 0) {
      getProducts(); // 全部
    } else {
      final category = _categories[index - 1];
      getProducts(categoryId: category.id);
    }
  }

  // 初始化数据
  Future<void> _initData() async {
    await getCategories();
    int categoryId = 0;
    if (categoryIndex > 0) {
      categoryId = _categories[categoryIndex - 1].id;
    }
    await getProducts(categoryId: categoryId); // 默认加载全部商品

    _tabController = TabController(
      length: _categories.length + 1, // 全部 + 分类
      vsync: this,
    );
    _tabController!.addListener(_handleTabChange);
  }

  // 加载分类
  Future<void> getCategories() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final data = await _api.categories();
      if (mounted) {
        setState(() {
          _categories = data;
        });
      }
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  // 加载商品列表
  Future<void> getProducts({int? categoryId}) async {
    final key = categoryId ?? 0;
    // 先看缓存
    if (_cache.containsKey(key)) {
      setState(() => _list = _cache[key]!);
      return;
    }

    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final data = await _api.list(categoryId: categoryId);
      if (mounted) {
        setState(() {
          _list = data;
          _cache[key] = data; // 缓存
        });
      }
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 👈 必须调用
    return DefaultTabController(
      length: max(1, _categories.length + 1), // 至少一个Tab
      child: Scaffold(
        appBar: AppBar(
          title: Container(
            decoration: const BoxDecoration(color: Colors.white),
            child: InkWell(
              onTap: () => Get.toNamed('/search_page'),
              child: TextField(
                enabled: false,
                decoration: InputDecoration(
                  hintText: '输入搜索内容',
                  isCollapsed: true,
                  contentPadding: const EdgeInsets.symmetric(
                    vertical: 12,
                    horizontal: 12,
                  ),
                  prefixIcon: const Icon(Icons.search),
                  border: InputBorder.none,
                  filled: true,
                  fillColor: Colors.grey.withValues(alpha: 0.1),
                ),
              ),
            ),
          ),
          bottom: TabBar(
            isScrollable: true,
            tabAlignment: TabAlignment.start,
            controller: _tabController,
            onTap: (index) {
              setState(() {
                categoryIndex = index;
              });
            },
            tabs: [
              const Tab(text: '全部'),
              for (var item in _categories) Tab(text: item.name),
            ],
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            _buildProductGrid(),
            for (var item in _categories) _buildProductGrid(),
          ],
        ),
      ),
    );
  }

  Widget _buildProductGrid() {
    if (_loading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_error != null) {
      return Center(
        child: TextButton(
          onPressed: _initData,
          child: Text('加载失败，点击重试\n$_error', textAlign: TextAlign.center),
        ),
      );
    }
    return RefreshIndicator(
      onRefresh: _initData,
      child: _list.isEmpty
          ? ListView(
              // 用 ListView 保证 RefreshIndicator 能触发
              children: [
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.5,
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(
                          Icons.shopping_bag_outlined,
                          size: 64,
                          color: Colors.grey,
                        ),
                        const SizedBox(height: 12),
                        const Text(
                          '暂无商品',
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            )
          : GridView.builder(
              padding: const EdgeInsets.all(12),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 10,
                crossAxisSpacing: 10,
                childAspectRatio: 0.7,
              ),
              itemCount: _list.length,
              itemBuilder: (context, index) {
                final item = _list[index];
                final defaultSku = item.skus.firstWhere(
                  (sku) => sku.id.toString() == item.defaultSkuId.toString(),
                );
                final price = defaultSku.price.toString();

                return InkWell(
                  onTap: () => Get.toNamed('/detail', arguments: item.id),
                  child: ProductCard(
                    imageUrl: item.imageUrl.split(",")[0],
                    name: item.name,
                    price: price,
                    sales: item.sales,
                  ),
                );
              },
            ),
    );
  }
}
